﻿Option Explicit On
Option Strict On


''' <summary>
''' Objeto para gestionar una agenda de nota
''' Francisco Jua Royo Bua 26/01/2012:
'''        Modificación de la visualización del data grid.
''' Francisco Jua Royo Bua 29/01/2012:
'''        Modificación del desplazamiento y arreglo.
''' </summary>
''' <remarks>Francisco Juan Royo Bua</remarks>
Public Class ObjSemana

#Region "atributos"


    Private _myBaseDatos As BBDDCita ''la base de datos de consulta
    Private _LisataFecha As List(Of String)


    Private _labelHoras As Label
    Private _labelLunes As Label
    Private _labelMartes As Label
    Private _labelMiercoles As Label
    Private _labelJueves As Label
    Private _labelViernes As Label
    Private _labelSabado As Label
    Private _labelDomingo As Label
    Private _labelEmpleado As Label
    Private _DataGridCalendario As DataGridView
    Private _Panel As Panel
    Private _Panel1 As Panel
    Private _panel2 As Panel

    'atributos de tiempo
    Private _IntervaloTiempo As Integer
    Private _diaSemana As _diasSemana
    Public Enum _diasSemana As Integer
        Lunes = 1
        Martes = 2
        Miercoles = 3
        Jueves = 4
        Viernes = 5
        Sabado = 6
        Domingo = 7
    End Enum

    'boolean
    Private _AutoAjusteDataGrid As Boolean

    'tamaño y posición
    Private _ancho As Integer
    Private _alto As Integer
    Private _x As Integer
    Private _y As Integer
    Private _Empleados As Integer

    'colores tarde y mañana y otros
    Private _ColorManyana As Color
    Private _ColorTarde As Color
    Private _ColorImpar As Color
    Private _ColorPar As Color
    Private _ColorImparSelec As Color
    Private _ColorParSelec As Color
    Private _Visible As Boolean

    'costante
    Private Const CARACTER_TOKEN = 185 'esto es para la creación de cadenas
#End Region

#Region "Contructores y destructores"


    Public Sub New(ByVal control As Control)

        _ancho = 200
        _alto = 200
        _x = 0
        _y = 0
        _Empleados = 1
        _ColorManyana = Color.Gold
        _ColorTarde = Color.LightGray
        _ColorImpar = Color.LawnGreen
        _ColorPar = Color.GreenYellow
        _ColorImparSelec = Color.Red
        _ColorParSelec = Color.Coral
        _IntervaloTiempo = 15
        _diaSemana = _diasSemana.Domingo
        _Visible = True

        Me.CrearPanel(control)
        Me.CrearControlesLabel(_Panel1)
        Me.CrearControlDataGriew(_panel2)
        Me.CrearLabel(_Panel1)
        Me._AutoAjusteDataGrid = True 'ajustará las dimensiones del data grid automaticamente

        Me.PintarCentro()

        Me.AutoRedimensionDataGrid()

        _myBaseDatos = New BBDDCita
        _LisataFecha = New List(Of String)
    End Sub


    Public Sub New(ByVal control As Control, ByVal Empleados As Integer)

        _ancho = 200
        _alto = 200
        _x = 0
        _y = 0
        _Empleados = Empleados
        _ColorManyana = Color.Gold
        _ColorTarde = Color.LightGray
        _ColorImpar = Color.LawnGreen
        _ColorPar = Color.GreenYellow
        _ColorImparSelec = Color.Red
        _ColorParSelec = Color.Coral
        _IntervaloTiempo = 15
        _diaSemana = _diasSemana.Domingo
        _Visible = True

        Me.CrearPanel(control)
        Me.CrearControlesLabel(_Panel1)
        Me.CrearControlDataGriew(_panel2)
        Me.CrearLabel(_Panel1)
        Me._AutoAjusteDataGrid = True 'ajustará las dimensiones del data grid automaticamente

        Me.PintarCentro()

        Me.AutoRedimensionDataGrid()

        _myBaseDatos = New BBDDCita
        _LisataFecha = New List(Of String)
    End Sub

    Public Sub New(ByVal control As Control, ByVal Empleados As Integer, ByVal diaSemana As _diasSemana)

        _ancho = 200
        _alto = 200
        _x = 0
        _y = 0
        _Empleados = Empleados
        _ColorManyana = Color.Gold
        _ColorTarde = Color.LightGray
        _ColorImpar = Color.LawnGreen
        _ColorPar = Color.GreenYellow
        _ColorImparSelec = Color.Red
        _ColorParSelec = Color.Coral
        _IntervaloTiempo = 15
        _diaSemana = diaSemana
        _Visible = True

        Me.CrearPanel(control)
        Me.CrearControlesLabel(_Panel1)
        Me.CrearControlDataGriew(_panel2)
        Me.CrearLabel(_Panel1)
        Me._AutoAjusteDataGrid = True 'ajustará las dimensiones del data grid automaticamente

        Me.PintarCentro()

        Me.AutoRedimensionDataGrid()

        _myBaseDatos = New BBDDCita
        _LisataFecha = New List(Of String)
    End Sub


    Public Sub New(ByVal control As Control, ByVal ColorManyna As Color, ByVal ColorTarde As Color, ByVal Empleados As Integer, ByVal DiasSemana As _diasSemana)

        _ancho = 200
        _alto = 200
        _x = 0
        _y = 0
        _Empleados = Empleados
        _ColorManyana = ColorManyna
        _ColorTarde = ColorTarde
        _ColorImpar = Color.LawnGreen
        _ColorPar = Color.GreenYellow
        _ColorImparSelec = Color.Red
        _ColorParSelec = Color.Coral
        _IntervaloTiempo = 15
        _diaSemana = DiasSemana
        _Visible = True

        Me.CrearPanel(control)
        Me.CrearControlesLabel(_Panel1)
        Me.CrearControlDataGriew(_panel2)
        Me.CrearLabel(_Panel1)
        Me._AutoAjusteDataGrid = True 'ajustará las dimensiones del data grid automaticamente

        Me.PintarCentro()

        Me.AutoRedimensionDataGrid()

        _myBaseDatos = New BBDDCita
        _LisataFecha = New List(Of String)
    End Sub




    Public Sub New(ByVal control As Control, ByVal Ancho As Integer, ByVal Alto As Integer, ByVal posX As Integer, ByVal posY As Integer, ByVal ColorManyna As Color, ByVal ColorTarde As Color, ByVal Empleados As Integer, ByVal DiasSemana As _diasSemana)

        _ancho = Ancho
        _alto = Alto
        _x = posX
        _y = posY
        _Empleados = Empleados
        _ColorManyana = ColorManyna
        _ColorTarde = ColorTarde
        _ColorImpar = Color.LawnGreen
        _ColorPar = Color.GreenYellow
        _ColorImparSelec = Color.Red
        _ColorParSelec = Color.Coral
        _IntervaloTiempo = 15
        _diaSemana = DiasSemana
        _Visible = True

        Me.CrearPanel(control)
        Me.CrearControlesLabel(_Panel1)
        Me.CrearControlDataGriew(_panel2)
        Me.CrearLabel(_Panel1)
        Me._AutoAjusteDataGrid = True 'ajustará las dimensiones del data grid automaticamente

        Me.PintarCentro()

        Me.AutoRedimensionDataGrid()
        _myBaseDatos = New BBDDCita
        _LisataFecha = New List(Of String)
    End Sub

#End Region

#Region "get y set"

    Public ReadOnly Property Labelunes As Label
        Get
            Return _labelLunes
        End Get
    End Property

    Public Property Visible As Boolean
        Get
            Return _Visible
        End Get
        Set(ByVal value As Boolean)
            _Visible = value
            _Panel.Visible = _Visible
        End Set
    End Property

    Public Property DiasSemana As _diasSemana
        Get
            Return _diaSemana
        End Get
        Set(ByVal value As _diasSemana)
            _diaSemana = value
        End Set
    End Property

    Public ReadOnly Property IntervaloTiempo As Integer
        Get
            Return _IntervaloTiempo
        End Get

    End Property

    Public Property ColorMañana() As Color
        Get
            Return _ColorManyana
        End Get
        Set(ByVal value As Color)
            _ColorManyana = value
        End Set
    End Property


    Public Property ColorTarde() As Color
        Get
            Return _ColorTarde
        End Get
        Set(ByVal value As Color)
            _ColorTarde = value
        End Set
    End Property



    Public Property DataGriewCalendario() As DataGridView
        Get
            Return _DataGridCalendario
        End Get
        Set(ByVal value As DataGridView)
            _DataGridCalendario = value
        End Set
    End Property

    Public Property AutoAjuste() As Boolean
        Get
            Return _AutoAjusteDataGrid
        End Get
        Set(ByVal value As Boolean)
            _AutoAjusteDataGrid = value
        End Set
    End Property

    'Public Property Panel() As Panel
    '    Get
    '        Return _Panel
    '    End Get
    '    'Set(ByVal value As Panel)

    '    'End Set
    '    Set(ByVal value As Panel)

    '    End Set
    'End Property

    Public Property Ancho As Integer
        Get
            Return _ancho
        End Get
        Set(ByVal value As Integer)
            _ancho = value
            _Panel.Width = _ancho
            _panel2.Width = _ancho
        End Set
    End Property

    Public Property Alto As Integer
        Get
            Return _alto
        End Get
        Set(ByVal value As Integer)
            _alto = value
            _Panel.Height = _alto
            _panel2.Height = _alto - 60
        End Set
    End Property

    Public Property X As Integer
        Get
            Return _x
        End Get
        Set(ByVal value As Integer)
            _x = value
            _Panel.Location = New Point(value, _y)
        End Set
    End Property

    Public Property Y As Integer
        Get
            Return _y
        End Get
        Set(ByVal value As Integer)
            _y = value
            _Panel.Location = New Point(_x, value)
        End Set
    End Property

    Public ReadOnly Property Empleado As Integer
        Get
            Return _Empleados
        End Get

    End Property

#End Region

#Region "Metodos publicos"

    ''' <summary>
    ''' Coloca el panel en su sitio
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub RecolocarPanel()
        _panel2.VerticalScroll.Value = 2
    End Sub

    ''' <summary>
    ''' comprobar si sale de rango
    ''' </summary>
    ''' <param name="DiasSemana"></param>
    ''' <param name="HoraInicio"></param>
    ''' <param name="CodEmpleado"></param>
    ''' <param name="UndTiempo"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function EstaRango(ByVal DiasSemana As _diasSemana, ByVal HoraInicio As String, ByVal CodEmpleado As Integer, ByVal UndTiempo As Integer) As Boolean

        Dim ok As Boolean = True

        Dim valorDiaSemana As Integer = 0
        Dim valorHora As Integer = 0
        'dar un valor al día semana
        valorDiaSemana = DiasSemana - 1
        'recorre todo el calendario en busca del valor de la hora en el índice
        For indiceFila = 0 To _DataGridCalendario.Rows.Count - 1
            If _DataGridCalendario.Rows(indiceFila).Cells(0).Value.ToString = HoraInicio Then

                valorHora = indiceFila
                indiceFila = _DataGridCalendario.Rows.Count + 10
            End If
        Next

        'ahora averiguar la celda a pintar gracias al id del empleado y día semana
        Dim indiceCelda As Integer = (CodEmpleado) + (valorDiaSemana * _Empleados)

        'ahora comproba si no falla
        Try
            Dim auxValorHora As Integer = 0
            Dim valor As Integer = 0
            For indiceFila = 0 To UndTiempo
                auxValorHora = valorHora + indiceFila
                valor = _DataGridCalendario.Rows(auxValorHora).Cells.Count
            Next
        Catch
            ok = False
        End Try

        Return ok
    End Function

    ''' <summary>
    ''' Retorna la Fecha De la Semana
    ''' </summary>
    ''' <param name="DiaSemana"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function RetornaFecha(ByVal DiaSemana As _diasSemana) As String

        Return _LisataFecha(DiaSemana)

    End Function


    Public Function AnchoTotal() As Integer

        Return _labelHoras.Width + (_labelLunes.Width * 7)

    End Function
    ''' <summary>
    ''' Esto Colorea los días selecionados
    ''' </summary>
    ''' <param name="DiasSemana">selecciona el dia de la semana </param>
    ''' <param name="HoraInicio">La hora de inicio</param>
    ''' <param name="CodEmpleado">el codigo del empleado</param>
    ''' <param name="UndTiempo">y la cantida de tiempo en unidades ejemplo(1 = 15'' , 2 = 30'')</param>
    ''' <remarks></remarks>
    Public Sub DibujarCitas(ByVal DiasSemana As _diasSemana, ByVal HoraInicio As String, ByVal CodEmpleado As Integer, ByVal UndTiempo As Integer)
        Dim valorDiaSemana As Integer = 0
        Dim valorHora As Integer = 0
        'dar un valor al día semana
        valorDiaSemana = DiasSemana - 1
        'recorre todo el calendario en busca del valor de la hora en el índice
        For indiceFila = 0 To _DataGridCalendario.Rows.Count - 1
            If _DataGridCalendario.Rows(indiceFila).Cells(0).Value.ToString = HoraInicio Then

                valorHora = indiceFila
                indiceFila = _DataGridCalendario.Rows.Count + 10
            End If
        Next

        'ahora averiguar la celda a pintar gracias al id del empleado y día semana
        Dim indiceCelda As Integer = (CodEmpleado) + (valorDiaSemana * _Empleados)

        'ahora pintamos
        Dim auxValorHora As Integer = 0
        For indiceFila = 0 To UndTiempo
            auxValorHora = valorHora + indiceFila
            If indiceCelda Mod 2 = 0 Then
                _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.BackColor = _ColorParSelec
            Else
                _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.BackColor = _ColorImparSelec
            End If

        Next
    End Sub

    ''' <summary>
    ''' Esto Colorea los dias selecionados con la información basica  de  la cita
    ''' </summary>
    ''' <param name="DiasSemana">selecciona el dia de la semana </param>
    ''' <param name="HoraInicio">La hora de inicio</param>
    ''' <param name="CodEmpleado">el codigo del empleado</param>
    ''' <param name="UndTiempo">y la cantida de tiempo en unidades ejemplo(1 = 15'' , 2 = 30'')</param>
    ''' <param name="informacion">Guarda cualquier informacion que se desea</param>
    ''' <remarks></remarks>
    Public Function DibujarCitasInformacion(ByVal DiasSemana As _diasSemana, ByVal HoraInicio As String, ByVal CodEmpleado As Integer, ByVal UndTiempo As Integer, ByVal informacion As String) As Boolean
        Dim ok As Boolean = True

        Dim valorDiaSemana As Integer = 0
        Dim valorHora As Integer = 0
        'comprobar si se puede fibujar
        If Me.EstaOcupado(DiasSemana, HoraInicio, CodEmpleado, UndTiempo) Then
            'dar un valor al día semana
            valorDiaSemana = DiasSemana - 1
            'recorre todo el calendario en busca del valor de la hora en el índice
            For indiceFila = 0 To _DataGridCalendario.Rows.Count - 1
                If _DataGridCalendario.Rows(indiceFila).Cells(0).Value.ToString = HoraInicio Then

                    valorHora = indiceFila
                    indiceFila = _DataGridCalendario.Rows.Count + 10
                End If
            Next

            'ahora averiguar la celda a pintar gracias al id del empleado y día semana
            Dim indiceCelda As Integer = (CodEmpleado) + (valorDiaSemana * _Empleados)

            'ahora pintamos
            Dim auxValorHora As Integer = 0
            For indiceFila = 0 To UndTiempo - 1
                auxValorHora = valorHora + indiceFila
                'guardar texto
                _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Value = informacion
                If indiceCelda Mod 2 = 0 Then
                    _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.BackColor = _ColorParSelec
                    _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.ForeColor = _ColorParSelec
                Else
                    _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.BackColor = _ColorImparSelec
                    _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.ForeColor = _ColorImparSelec
                End If
            Next
        Else
            ok = False
        End If

        Return ok

    End Function
    ''' <summary>
    ''' Establece el rango de Horas de la agenda
    ''' </summary>
    ''' <param name="horaIncial">String del siguiente formato "00:00" por donde empieza</param>
    ''' <param name="horaFinal">String del siguiente formato "00:00" por donde termina</param>
    ''' <remarks>Francisco Juan Royo Bua - 21/01/2012</remarks>
    Public Sub EstaBlecerRangoHoras(ByVal horaIncial As String, ByVal horaFinal As String)

        Dim hora As Integer = CInt(horaIncial.Substring(0, 2))
        Dim horaF As Integer = CInt(horaFinal.Substring(0, 2))
        Dim valorComparar As Integer

        'primero el intervalo de horas 
        Dim ultimoIndice As Integer = -1
        For indiceFilas = 0 To _DataGridCalendario.Rows.Count - 1
            Try
                valorComparar = CInt(_DataGridCalendario.Rows(indiceFilas).Cells(0).Value.ToString.Substring(0, 2))
                If valorComparar >= hora And valorComparar <= horaF Then
                    ultimoIndice = indiceFilas
                Else
                    _DataGridCalendario.Rows.RemoveAt(indiceFilas)
                    If indiceFilas = 0 Then
                        indiceFilas = ultimoIndice
                    Else
                        indiceFilas = ultimoIndice - 1
                    End If
                    'Else
                    '    _DataGridCalendario.Rows(x).Visible = False

                End If
            Catch

            End Try

        Next

        'ahora eliminamos los primeros que no cuadren con la hora
        Try
            For indiceFilas = 0 To _DataGridCalendario.Rows.Count - 1
                If horaIncial = _DataGridCalendario.Rows(indiceFilas).Cells(0).Value.ToString Then
                    indiceFilas = _DataGridCalendario.Rows.Count + 10
                Else
                    _DataGridCalendario.Rows.RemoveAt(indiceFilas)
                    indiceFilas = -1
                    'Else
                    '    _DataGridCalendario.Rows(x).Visible = False

                End If
            Next
        Catch

        End Try



        'ahora eliminamos los primeros que no cuadren con la hora
        Try
            For indiceFilas = _DataGridCalendario.Rows.Count - 1 To 0 Step -1
                If horaFinal = _DataGridCalendario.Rows(indiceFilas).Cells(0).Value.ToString Then
                    indiceFilas = -1
                Else
                    _DataGridCalendario.Rows.RemoveAt(indiceFilas)
                    indiceFilas = _DataGridCalendario.Rows.Count
                    'Else
                    '    _DataGridCalendario.Rows(x).Visible = False

                End If
            Next
        Catch

        End Try


        Me.AutoRedimensionDataGrid()

    End Sub

    ''' <summary>
    ''' Limpia el calendario
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Limpiar()
        Me.PintarCentro()
    End Sub

#End Region

#Region "Metodos privados"

    ''' <summary>
    ''' comprobar si se puede guardar el dato
    ''' </summary>
    ''' <param name="DiasSemana"></param>
    ''' <param name="HoraInicio"></param>
    ''' <param name="CodEmpleado"></param>
    ''' <param name="UndTiempo"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function EstaOcupado(ByVal DiasSemana As _diasSemana, ByVal HoraInicio As String, ByVal CodEmpleado As Integer, ByVal UndTiempo As Integer) As Boolean

        Dim ok As Boolean = True

        Dim valorDiaSemana As Integer = 0
        Dim valorHora As Integer = 0
        'dar un valor al día semana
        valorDiaSemana = DiasSemana - 1
        'recorre todo el calendario en busca del valor de la hora en el índice
        For indiceFila = 0 To _DataGridCalendario.Rows.Count - 1
            If _DataGridCalendario.Rows(indiceFila).Cells(0).Value.ToString = HoraInicio Then

                valorHora = indiceFila
                indiceFila = _DataGridCalendario.Rows.Count + 10
            End If
        Next

        'ahora averiguar la celda a pintar gracias al id del empleado y día semana
        Dim indiceCelda As Integer = (CodEmpleado) + (valorDiaSemana * _Empleados)

        'ahora comproba si no falla
        Try
            Dim auxValorHora As Integer = 0
            For indiceFila = 0 To UndTiempo
                auxValorHora = valorHora + indiceFila
                'guardar texto
                If indiceCelda Mod 2 = 0 Then
                    If _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.BackColor = _ColorParSelec Then
                        ok = False
                        indiceFila = UndTiempo + 1
                    End If
                Else
                    If _DataGridCalendario.Rows(auxValorHora).Cells(indiceCelda).Style.BackColor = _ColorImparSelec Then
                        ok = False
                        indiceFila = UndTiempo + 1
                    End If
                End If
            Next
        Catch
            ok = False
        End Try

        Return ok
    End Function


    ''' <summary>
    ''' Crea una cadena para guardar en la celda del data grid
    ''' </summary>
    ''' <param name="horaInicio">La hora inicio string</param>
    ''' <param name="undTiempo">und tiempo string</param>
    ''' <param name="nombreCliente">nombre cliente string</param>
    ''' <param name="nombreEmpleado">nombre empleado string</param>
    ''' <param name="fecha">fecha date</param>
    ''' <returns>toda la información junta separada por un token</returns>
    ''' <remarks></remarks>
    Private Function CrearCadena(ByVal horaInicio As String, ByVal undTiempo As String, ByVal nombreCliente As String, ByVal nombreEmpleado As String, ByVal fecha As Date) As String
        Dim cadena As String = ""

        cadena = horaInicio & CChar(ChrW(CARACTER_TOKEN)) & undTiempo & CChar(ChrW(CARACTER_TOKEN)) & nombreCliente & CChar(ChrW(CARACTER_TOKEN)) & nombreEmpleado & CChar(ChrW(CARACTER_TOKEN)) & fecha.ToString("dd/MM/yyyy")

        Return cadena
    End Function

    Private Sub CrearPanel(ByVal control As Control)

        _Panel = New Panel
        With _Panel
            .Name = "Panel1"
            .Width = _ancho
            .Height = _alto
            .Location = New Point(_x, _y)
            .AutoScroll = False
            .AutoSize = False
            .Visible = _Visible
        End With

        'aqui esta el data grid
        _panel2 = New Panel
        With _panel2
            .Name = "Panel2"
            .Width = _ancho
            .Height = _alto - 50
            .Location = New Point(_x, _y + 50) '50 por que tiene dos label antes
            .AutoScroll = True
            .AutoSize = False
            .Visible = _Visible
        End With

        _Panel1 = New Panel
        With _Panel1
            .Name = "Panel"
            .Width = _ancho
            .Height = 50
            .Location = New Point(_x, _y)
            .AutoScroll = False
            .AutoSize = False
            .Visible = _Visible
            .BackColor = Color.Black
        End With

        'creación de un evento del panel2  para controlar el location del panel1
        AddHandler _panel2.Scroll, AddressOf _panel2_scroll

        control.Controls.Add(_Panel)
        _Panel.Controls.Add(_panel2)
        _Panel.Controls.Add(_Panel1)

    End Sub

    Private Sub CrearControlesLabel(ByVal control As Control)
        Dim anchoLabel As Integer = 100
        Dim altoLabel As Integer = 30
        Dim xLabel As Integer = 0
        Dim yLabel As Integer = 0
        Dim tamanyoTexto As Integer = 10
        Dim restarMargenDerecho As Integer = 1

        'Dependiendo la cantidad de empleados cambia el tamaño del ancho
        If _Empleados > 2 Then
            anchoLabel = 25 * _Empleados
        End If

        Dim rojo As Byte = Color.Aquamarine.R
        Dim verde As Byte = Color.Aquamarine.G
        Dim azul As Byte = CByte(Color.Aquamarine.B - 100)

        Dim nuevoColor As Color = Color.FromArgb(rojo, verde, azul)

        _labelHoras = New Label()
        With _labelHoras
            .Name = "labelHoras"
            .Text = "Horas"
            .Width = 85
            .Height = altoLabel
            .Location = New Point(xLabel, yLabel)
            .Visible = True
            .BackColor = nuevoColor
            .TextAlign = ContentAlignment.MiddleCenter
            .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        End With
        control.Controls.Add(_labelHoras)

        _labelEmpleado = New Label()
        With _labelEmpleado
            .Name = "labelEmpleados"
            .Text = "Empleados"
            .Width = 85
            .Height = altoLabel - 10
            .Location = New Point(xLabel, yLabel + 30) 'para ponerlo de bajo del label hora
            .Visible = True
            .BackColor = Color.Aqua
            .TextAlign = ContentAlignment.MiddleCenter
            .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        End With
        control.Controls.Add(_labelEmpleado)

        xLabel = 85 - anchoLabel

        azul = CByte(azul + 15)
        nuevoColor = Color.FromArgb(rojo, verde, azul)

        If _diasSemana.Lunes <= _diaSemana Then
            _labelLunes = New Label()
            With _labelLunes
                .Name = "labelLunes"
                .Text = "Lunes"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + anchoLabel, yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With

            control.Controls.Add(_labelLunes)
            azul = CByte(azul + 15)
            nuevoColor = Color.FromArgb(rojo, verde, azul)
        End If

        If _diasSemana.Martes <= _diaSemana Then

            _labelMartes = New Label()
            With _labelMartes
                .Name = "labeMartes"
                .Text = "Martes"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + (anchoLabel * 2), yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With
            azul = CByte(azul + 15)
            nuevoColor = Color.FromArgb(rojo, verde, azul)
            control.Controls.Add(_labelMartes)
        End If

        If _diasSemana.Miercoles <= _diaSemana Then
            _labelMiercoles = New Label()
            With _labelMiercoles
                .Name = "labelMiercoles"
                .Text = "Miercoles"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + (anchoLabel * 3), yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With
            azul = CByte(azul + 15)
            nuevoColor = Color.FromArgb(rojo, verde, azul)
            control.Controls.Add(_labelMiercoles)

        End If

        If _diasSemana.Jueves <= _diaSemana Then

            _labelJueves = New Label()
            With _labelJueves
                .Name = "labelJueves"
                .Text = "Jueves"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + (anchoLabel * 4), yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With
            azul = CByte(azul + 15)
            nuevoColor = Color.FromArgb(rojo, verde, azul)
            control.Controls.Add(_labelJueves)
        End If

        If _diasSemana.Viernes <= _diaSemana Then

            _labelViernes = New Label()
            With _labelViernes
                .Name = "labelViernes"
                .Text = "Viernes"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + (anchoLabel * 5), yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With
            azul = CByte(azul + 15)
            nuevoColor = Color.FromArgb(rojo, verde, azul)
            control.Controls.Add(_labelViernes)
        End If

        If _diasSemana.Sabado <= _diaSemana Then
            _labelSabado = New Label()
            With _labelSabado
                .Name = "labelSabado"
                .Text = "Sabado"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + (anchoLabel * 6), yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With
            azul = CByte(azul + 15)
            nuevoColor = Color.FromArgb(rojo, verde, azul)
            control.Controls.Add(_labelSabado)
        End If

        If _diasSemana.Domingo <= _diaSemana Then

            _labelDomingo = New Label()
            With _labelDomingo
                .Name = "labelDomingo"
                .Text = "Domingo"
                .Width = anchoLabel - restarMargenDerecho
                .Height = altoLabel
                .Location = New Point(xLabel + (anchoLabel * 7), yLabel)
                .Visible = True
                .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
                .BackColor = nuevoColor
                .TextAlign = ContentAlignment.MiddleCenter
            End With

            control.Controls.Add(_labelDomingo)
        End If

        'una vez dibujado los label le damos el ancho real al panel1
        _Panel1.Width = _labelHoras.Width + (anchoLabel * _diaSemana)

    End Sub

    Private Sub CrearControlDataGriew(ByVal control As Control)
        _DataGridCalendario = New DataGridView
        Dim ancho As Integer = 100
        Dim alto As Integer = 20

        'Dependiendo la cantidad de empleados cambia el tamaño del ancho
        If _Empleados = 2 Then
            ancho = 50
        ElseIf _Empleados > 2 Then
            ancho = 25
        End If

        With _DataGridCalendario
            .Name = "DataGridCalendario"
            .BorderStyle = BorderStyle.None
            .ColumnHeadersVisible = False
            .RowHeadersVisible = False
            .Width = _labelHoras.Width + (_labelLunes.Width * _diaSemana)
            .Height = 25 * 96
            .Location = New Point(0, 0)
            '.CellBorderStyle = DataGridViewCellBorderStyle.None
            .CellBorderStyle = DataGridViewCellBorderStyle.SunkenHorizontal
            .Enabled = True
            .MultiSelect = False
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .TabStop = False
        End With
        'crea más o menos dependiendo los empleados
        _DataGridCalendario.Columns.Add("Colum" & 0, "")
        _DataGridCalendario.Columns(0).Width = 85
        _DataGridCalendario.Columns(0).ReadOnly = True
        _DataGridCalendario.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        For indiceColumns = 1 To (_diaSemana * _Empleados)
            _DataGridCalendario.Columns.Add("Colum" & X, "")
            _DataGridCalendario.Columns(indiceColumns).Width = ancho
            _DataGridCalendario.Columns(indiceColumns).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        Next

        Dim intervalofijo As Integer = _IntervaloTiempo
        Dim horas As Integer = 0
        Dim minutos As Integer = 0
        Dim intervaloVariado As String

        For indiceRows = 0 To 95
            _DataGridCalendario.Rows.Add()
            _DataGridCalendario.Rows(indiceRows).Height = alto

            minutos += intervalofijo

            If indiceRows Mod 4 = 0 Then
                horas += 1
                minutos = 0
            End If

            If horas = 24 Then
                intervaloVariado = "00:" & minutos.ToString("00")
            Else
                intervaloVariado = horas.ToString("00") & ":" & minutos.ToString("00")

            End If
            _DataGridCalendario.Rows(indiceRows).SetValues(intervaloVariado)
            'Las cambiamos de color para diferenciarlas con la tarde
            If horas >= 15 Then
                _DataGridCalendario.Rows(indiceRows).Cells(0).Style.BackColor = Me._ColorTarde
            Else
                _DataGridCalendario.Rows(indiceRows).Cells(0).Style.BackColor = Me._ColorManyana
            End If
        Next

        'crear eventos
        AddHandler _DataGridCalendario.CellMouseEnter, AddressOf _DataGridCalendario_CellMouseEnter
        AddHandler _DataGridCalendario.CellMouseClick, AddressOf _DataGridCalendario_cellMouseClick
        control.Controls.Add(_DataGridCalendario)

    End Sub
    ''' <summary>
    ''' Pinta las celdas del interior 
    ''' </summary>
    ''' <remarks>Francisco Juan Royo Bua -> 23/01/2012</remarks>
    Private Sub PintarCentro()

        Dim nuevaCelda As New DataGridViewAdvancedBorderStyle
        Dim nuevaCelda2 As New DataGridViewAdvancedBorderStyle
        'nuevaCelda.Top = DataGridViewAdvancedCellBorderStyle.None
        nuevaCelda.Right = DataGridViewAdvancedCellBorderStyle.Single
        nuevaCelda2.All = DataGridViewAdvancedCellBorderStyle.Single

        For indiceFila = 0 To _DataGridCalendario.Rows.Count - 1
            For indiceColumna = 1 To _DataGridCalendario.Rows(indiceFila).Cells.Count - 1
                If indiceColumna Mod 2 = 0 Then
                    _DataGridCalendario.Rows(indiceFila).Cells(indiceColumna).Style.BackColor = _ColorPar
                    _DataGridCalendario.Rows(indiceFila).Cells(indiceColumna).Value = ""
                    '_DataGridCalendario.Rows(indiceFila).Cells(indiceColumna).AdjustCellBorderStyle(nuevaCelda, nuevaCelda, False, False, False, False)
                Else
                    _DataGridCalendario.Rows(indiceFila).Cells(indiceColumna).Style.BackColor = _ColorImpar
                    _DataGridCalendario.Rows(indiceFila).Cells(indiceColumna).Value = ""
                End If
            Next
        Next

    End Sub

    ''' <summary>
    ''' Su uso es después de crear los controles del data grid y label
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub AutoRedimensionDataGrid()

        Dim anchoData As Integer
        Dim altoData As Integer
        'Comprobar si tiene permiso
        If _AutoAjusteDataGrid Then

            anchoData = _labelHoras.Width + ((_labelLunes.Width + 1) * _diaSemana)
            'calcular el alto
            If _DataGridCalendario.Rows.Count >= 1 Then
                altoData += _DataGridCalendario.Rows(0).Height * _DataGridCalendario.Rows.Count
            Else
                altoData = 0
            End If

            _DataGridCalendario.Width = anchoData
            _DataGridCalendario.Height = altoData
        End If

    End Sub

    Private Sub CrearLabel(ByVal control As Control)

        Dim texto As String
        Dim multiplo As Integer = 0
        Dim restarAncho As Integer = 0

        For indice = 1 To _DataGridCalendario.Columns.Count - 1
            With _DataGridCalendario

                If indice > _Empleados Then
                    texto = CStr(indice - _Empleados * multiplo)
                Else
                    texto = CStr(indice)
                End If

                'cada paso del empleado se amplia el multiplo
                If indice Mod _Empleados = 0 Then
                    multiplo += 1
                End If

                If indice Mod _Empleados = 0 Then
                    restarAncho = 1
                Else
                    restarAncho = 0
                End If

                If indice Mod 2 = 0 Then
                    CrearNuevoLabel(control, texto, "labMenu_" & indice, .Columns(indice).Width - restarAncho, .Rows(0).Height, _labelEmpleado.Width + .Columns(indice).Width * (indice - 1), _labelEmpleado.Location.Y, _ColorPar)
                Else
                    CrearNuevoLabel(control, texto, "labMenu_" & indice, .Columns(indice).Width - restarAncho, .Rows(0).Height, _labelEmpleado.Width + .Columns(indice).Width * (indice - 1), _labelEmpleado.Location.Y, _ColorImpar)
                End If

            End With
        Next

    End Sub

    Private Sub CrearNuevoLabel(ByVal control As Control, ByVal texto As String, ByVal name As String, ByVal valueAncho As Integer, ByVal valueAlto As Integer, _
                                ByVal xLabel As Integer, ByVal yLabel As Integer, ByVal color As Color)
        Dim tamanyoTexto As Integer = 10

        Dim nuevoLavel As New Label
        With nuevoLavel
            .Name = name
            .Text = texto
            .Width = valueAncho
            .Height = valueAlto
            .Location = New Point(xLabel, yLabel)
            .Visible = True
            .BackColor = color
            .TextAlign = ContentAlignment.MiddleCenter
            .Font = New System.Drawing.Font("Microsoft Sans Serif", tamanyoTexto, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        End With

        control.Controls.Add(nuevoLavel)

    End Sub

#End Region

#Region "Metodos Calculo tiempos"

    ''' <summary>
    ''' Rellena la lista de fechas
    ''' </summary>
    ''' <param name="FechaActual"></param>
    ''' <remarks></remarks>
    Public Sub CalcularFechas(ByVal FechaActual As Date)

        Dim nuevoTiempo As Date
        Dim Intervalo As Integer
        Dim Nueva As String = ""


        _LisataFecha.Clear()
        _LisataFecha.Add(Nueva)

        'conseguir los intervalos de tiempo
        'Calcular Lunes
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 1)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 1), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)

        'Calcular Martes
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 2)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 2), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)

        'Calcular Miercoles
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 3)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 3), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)

        'Calcular Jueves
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 4)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 4), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)

        'Calcular Viernes
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 5)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 5), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)

        'Calcular Sabado
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 6)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 6), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)

        'Calcular Domingo
        Intervalo = CalcularInterValoDia(FechaActual.DayOfWeek, 7)
        nuevoTiempo = DateAdd(DateInterval.Day, CalcularInterValoDia(FechaActual.DayOfWeek, 7), FechaActual)
        Nueva = nuevoTiempo.ToString("dd/MM/yyyy")
        _LisataFecha.Add(Nueva)


    End Sub

    Private Function CalcularInterValoDia(ByVal diaActual As Integer, ByVal diaCalcular As Integer) As Integer
        Dim resultado As Integer = 0
        resultado = diaCalcular - diaActual
        Return resultado
    End Function

#End Region

#Region "eventos"

    ''' <summary>
    ''' Despalaz el panel1  de pendiendo la pos del scrolvertical
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub _panel2_scroll(ByVal sender As Object, ByVal e As ScrollEventArgs)

        _Panel1.Location = New Point(0 - _panel2.HorizontalScroll.Value, 0)

    End Sub
    ''' <summary>
    ''' reupera la información del datagrid y abre la ventana de información de la cita
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e">contiene el indice de la celda y el indice de la columna</param>
    ''' <remarks>Francisco Juan Royo Bua 08/02/2012</remarks>
    Private Sub _DataGridCalendario_cellMouseClick(ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs)
        'controla si esta lleno o no el value
        Try
            If e.ColumnIndex = 0 Then

            Else
                If CDbl(_DataGridCalendario.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString) > 0 Then
                    'comprobar si esta visible para cerrarlo y abrilor de nuevo
                    If FormInforCita.Visible Then
                        FormInforCita.Close()
                        FormInforCita.iDcita = _myBaseDatos.BuscarCitaIdCita(CStr(_DataGridCalendario.Rows(e.RowIndex).Cells(e.ColumnIndex).Value))
                        FormInforCita.Show()
                    Else
                        FormInforCita.iDcita = _myBaseDatos.BuscarCitaIdCita(CStr(_DataGridCalendario.Rows(e.RowIndex).Cells(e.ColumnIndex).Value))
                        FormInforCita.Show()

                    End If

                End If
            End If

        Catch
            Form_Cita.Show()
        End Try
        _DataGridCalendario.Rows(0).Cells(0).Selected = True
        _DataGridCalendario.Enabled = False
        _DataGridCalendario.Enabled = True
    End Sub

    Private Sub _DataGridCalendario_CellMouseEnter(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)

    End Sub

#End Region

End Class
